# -*- coding:utf-8 -*-
import sys
import json
from flask import Flask, request, jsonify, url_for
from flask import render_template
from models import db, Questions
from models import Answers
from models import User
from schemas import ma, question_schema, questions_schema
from schemas import answer_schema, answers_schema
from flask_moment import Moment
# from flask_login import LoginManager, current_user, login_required

# login_manager = LoginManager()


app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///questions.db"
db.init_app(app)
ma.init_app(app)
moment = Moment(app)

# login_manager.init_app(app)


@app.route('/q/', methods=['GET'])
def list_q():
    '''
    获取问题列表
    '''
    all_q = Questions.query.all()
    return questions_schema.jsonify(all_q)


@app.route('/q/<id>')
def get_questions(id):
    '''
    获取一个问题详情
    '''
    q = Questions.query.get_or_404(id)
    return question_schema.jsonify(q)


@app.route('/q/', methods=["POST"])
def create_question():
    '''
    创建一个问题
    '''
    q, errors = question_schema.load(json.loads(request.data))
    if errors:
        resp = jsonify(errors)
        resp.status_code = 400
        return resp
    db.session.add(q)
    db.session.commit()

    resp = jsonify({'state': 'success', "message": "created"})
    resp.status_code = 201
    location = url_for('get_questions', id=q.id)
    resp.headers["Location"] = location
    return resp


@app.route('/q/<id>', methods=['POST'])
def edit_q(id):
    '''
    修改一个问题
    '''
    q = Questions.query.get_or_404(id)
    q, errors = question_schema.load(json.loads(request.data), instance=q)
    if errors:
        resp = jsonify(errors)
        resp.status_code = 400
        return resp

    db.session.add(q)
    db.session.commit()

    resp = jsonify({'state': 'success', "message": "updated"})
    resp.status_code = 201
    location = url_for('get_questions', id=q.id)
    resp.headers["Location"] = location

    return resp


@app.route('/q/<id>', methods=['DELETE'])
def delete_q(id):
    '''
    删除一个问题
    '''
    q = Questions.query.get_or_404(id)
    db.session.delete(q)
    db.session.commit()
    return jsonify({'state': 'success', 'message': 'deleted'})


@app.errorhandler(404)
def page_not_found(error):
    resp = jsonify({'error': 'not found'})
    resp.status_code = 404
    return resp


@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')


@app.route('/questions/<int:id>', methods=['GET'])
def detail(id):
    q = Questions.query.get_or_404(id)
    from datetime import datetime
    now = datetime.utcnow()
    return render_template('detail.html', id=id, q=q, now=now)


@app.route('/answers/', methods=['POST'])
def creat_answers():
    '''
    创建一个回答
    '''
    data = json.loads(request.data)
    a, errors = answer_schema.load(data)
    q = Questions.query.get_or_404(data.get('questions_id'))
    a.questions = q
    if errors:
        resp = jsonify(errors)
        resp.status_code = 400
        return resp
    db.session.add(a)
    db.session.commit()

    resp = jsonify({'state': 'success', "message": "created"})
    resp.status_code = 201
    location = url_for('get_answer', id=a.id)
    resp.headers["Location"] = location
    return resp


@app.route('/answers/<int:id>')
def get_answer(id):
    a = Answers.query.get_or_404(id)
    return answer_schema.jsonify(a)


@app.route('/answers_by_question/<int:id>', methods=['GET'])
def get_answer_by_question(id):
    q = Questions.query.get_or_404(id)
    print q
    return answer_schema.jsonify(q.answers)


if __name__ == "__main__":
    if "createdb" in sys.argv:
        with app.app_context():
            db.create_all()
        print("Database Created!")

    elif "seeddb" in sys.argv:
        with app.app_context():
            q1 = Questions(title='test question 1', descriptions='test')
            u = User(name='cary', api_key='test1')
            # q1 = Questions.query.get_or_404(1)
            # u = User.query.get_or_404(1)
            an = Answers(content='test', questions=q1, user=u)
            db.session.add(q1)
            db.session.add(an)
            db.session.commit()
        print("Database seeded")

    else:
        app.run(debug=True)
